package com.cgydu.controller;

import cn.dsna.util.images.ValidateCode;
import com.cgydu.annotation.ContentType;
import com.cgydu.entity.Message;
import com.cgydu.entity.User;
import com.cgydu.service.UserService;
import com.cgydu.service.impl.UserServiceImpl;
import com.cgydu.utils.Base64Utils;
import com.cgydu.utils.Constants;
import org.apache.commons.beanutils.BeanUtils;


import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.Map;


/**
 * projectName: day25_store
 * author: CGY
 * time: 2020/8/26 11:02
 * description:
 */
@WebServlet("/user")
public class UserController  extends BaseController {


    @ContentType("image/png")
    public void  retImg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //int width, int height, int codeCount, int lineCount

        ValidateCode validateCode = new ValidateCode(100,45,1,10);

        String code = validateCode.getCode(); //返回图片上的正确字符

        HttpSession session = request.getSession();
        session.setAttribute("code", code);
        ServletOutputStream outputStream = response.getOutputStream();
        validateCode.write(outputStream);

    }



    public String login(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {
        //1.获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //用户输入
        String code = request.getParameter("code");
        //是否自动登录
        String auto = request.getParameter("auto");


        HttpSession session = request.getSession();
        String rCode = (String)session.getAttribute("code");
        //2.调用业务逻辑

        //1.比验证码

        if (rCode.equalsIgnoreCase(code))
        {
            //验证码正确
            UserService userService = new UserServiceImpl();
            User user = userService.login(username,password);

            if (user != null)
            {
                //查到了
                if (user.getUstatus() == Constants.ACTIVE_SUCCESS) {

                    //可以登录

                    session.setAttribute("user", user);

//                    if (auto != null) {
//                        //自动登录
//                        Cookie cookie = new Cookie("user", user.getUsername()+"_"+user.getUpassword());
//                        cookie.setPath(request.getContextPath());
//                        cookie.setMaxAge(2*7*24*60*60);
//                        response.addCookie(cookie);
//                    }
                    if (auto == null){
                        //没有勾选！
                        //将本地浏览器的存储的cookie'清空'
                        Cookie cookie = new Cookie(Constants.AUTO_NAME,"");
                        cookie.setPath("/");
                        cookie.setMaxAge(0);
                        response.addCookie(cookie);
                    }else{
                        //自定登录数据库存储 2周
                        String content = username+ Constants.FLAG+password;
                        content = Base64Utils.encode(content);
                        Cookie cookie = new Cookie(Constants.AUTO_NAME,content);
                        cookie.setPath("/");
                        cookie.setMaxAge(14*24*60*60);
                        response.addCookie(cookie);
                    }


                    return Constants.REDIRECT_ACTION + "/index.jsp";

                }else{
                    session.setAttribute("msg","账号未激活，请激活后在登录！！");
                    return Constants.REDIRECT_ACTION + request.getContextPath()+"/login.jsp";
                }

            }else{
                //没有查到
                session.setAttribute("msg","账号或者密码错误！");
                return Constants.REDIRECT_ACTION + request.getContextPath()+"/login.jsp";
            }


        }else{

            session.setAttribute("msg","验证码错误！");
            return Constants.REDIRECT_ACTION + request.getContextPath()+"/login.jsp";
        }

    }


    /**
     * 检查账号是否存在的接口
     * @param request
     * @param response
     * @return message转成的json数据
     * @throws IOException
     */
    @ContentType("application/json;charset=utf-8")
    public Message checkUser(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {

        //1.获取请求参数
        String username = request.getParameter("username");
        //2.调用业务逻辑
        UserService userService = new UserServiceImpl();
        Message message = userService.checkUser(username);
        //3.响应
        return message;
    };




    public String register(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException, InvocationTargetException, IllegalAccessException {

        //1.获取请求参数
        // key  value  key value
        Map<String, String[]> map = request.getParameterMap();
        //将请求参数封装到实体类  更符合面向对象思想！
        //  input name的值  =====   http请求参数key    ====   map key  ===== 实体类的属性 驼峰式   ==不保证==  数据库列 _
        User user = new User();
        BeanUtils.populate(user, map);

        //2.调用业务逻辑
        UserService userService = new UserServiceImpl();
        int status = userService.register(user);

        //3.响应

        if (status == Constants.MESSAGE_FAIL)
        {
            request.getSession().setAttribute("registerMsg", "注册失败！稍后再试！");
            return Constants.REDIRECT_ACTION + request.getContextPath()+"/register.jsp";
        }

        return Constants.REDIRECT_ACTION + request.getContextPath()+"/registerSuccess.jsp";
    };



    public String active(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException, InvocationTargetException, IllegalAccessException {

        //1.获取请求参数
        //激活码
        String code = request.getParameter("c");

        //2.调用业务逻辑
        UserService userService = new UserServiceImpl();
        int status = userService.activeUser(code);


        //3.响应

        if (status == Constants.ACTIVE_SUCCESS)
        {

            return Constants.REDIRECT_ACTION + request.getContextPath()+"/login.jsp";
        }

        HttpSession session = request.getSession();

        if (status == Constants.HASED_ACTIVE)
        {
            session.setAttribute("msg","账号已经激活！请勿重复激活！");

        }else{
            session.setAttribute("msg","激活失败，请稍后再试！");
        }

        return Constants.REDIRECT_ACTION + request.getContextPath()+"/message.jsp";
    }
    /**
     * 注销登录！清空数据！跳转到登录页面
     * @param request
     * @param response
     * @return
     */
    public String logOut(HttpServletRequest request, HttpServletResponse response){

        //1.清空session中的用户数据
        HttpSession session = request.getSession();
        session.removeAttribute("loginUser");

        //2.清空和覆盖cookie存储的自动登录信息

        Cookie cookie = new Cookie(Constants.AUTO_NAME,"");
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        //3.转发到登录页面
        request.setAttribute("msg","注销登录成功！");
        return  Constants.FORWARD_ACTION+ "/login.jsp";
    }

}
